﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
using System.Runtime.Serialization;

namespace WcfCore
{
	public class NetDataContractSerializerOperationBehavior : DataContractSerializerOperationBehavior
	{
		public NetDataContractSerializerOperationBehavior(OperationDescription operation)
			: base(operation)
		{
		}

		public NetDataContractSerializerOperationBehavior(OperationDescription operation, DataContractFormatAttribute dataContractFormatAttribute)
			: base(operation, dataContractFormatAttribute)
		{
		}

		public override XmlObjectSerializer CreateSerializer(Type type, string name, string ns,
			IList<Type> knownTypes)
		{
			return new NetDataContractSerializer(name, ns);
		}

		public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name,
			XmlDictionaryString ns, IList<Type> knownTypes)
		{
			return new NetDataContractSerializer(name, ns);
		}
	}

	public class NetDataContractSerializerFormatAttribute : Attribute, IOperationBehavior
	{
		public void AddBindingParameters(OperationDescription description, BindingParameterCollection parameters)
		{
		}

		public void ApplyClientBehavior(OperationDescription description,
			System.ServiceModel.Dispatcher.ClientOperation proxy)
		{
			ReplaceDataContractSerializerOperationBehavior(description);
		}

		public void ApplyDispatchBehavior(OperationDescription description,
			System.ServiceModel.Dispatcher.DispatchOperation dispatch)
		{
			ReplaceDataContractSerializerOperationBehavior(description);
		}

		public void Validate(OperationDescription description)
		{
		}

		private static void ReplaceDataContractSerializerOperationBehavior(OperationDescription description)
		{
			DataContractSerializerOperationBehavior dcsOperationBehavior =
			description.Behaviors.Find<DataContractSerializerOperationBehavior>();

			if (dcsOperationBehavior != null)
			{
				description.Behaviors.Remove(dcsOperationBehavior);
				description.Behaviors.Add(new NetDataContractSerializerOperationBehavior(description));
			}
		}
	}
}